package com.cdd.agent.api.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cdd.common.constant.RedisKeys;
import com.cdd.common.core.redis.RedisCache;
import com.cdd.common.domain.entity.AppUser;
import com.cdd.agent.api.mapper.AppUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @author cdd
 * @date 2025-08-08 10:56
 */
@Service
public class AppUserService {

    @Resource
    private AppUserMapper appUserMapper;

    @Resource
    private RedisCache redisCache;

    public AppUserMapper getBaseMapper() {
        return appUserMapper;
    }

    public AppUser get(Integer userId) {
        return appUserMapper.selectById(userId);
    }

    public AppUser findByUser(String loginname, String password) {
        return appUserMapper.selectOne(
                new LambdaQueryWrapper<AppUser>()
                        .eq(AppUser::getLoginname, loginname)
                        .eq(AppUser::getPassword, password)
        );
    }

    /**
     * 账号状态修改
     * @param id
     * @param state
     */
    public void upstate(Integer id, Integer state, Integer hour) {
        AppUser appUser = appUserMapper.selectById(id);
        Assert.notNull(appUser, "用户不存在");
        if(state == 2 && hour != null) {
            //-1为永久禁止 不做redis超时监听
            if(hour != -1) {
                String key = String.format(RedisKeys.FORBID_USER_LOGIN, id);
                redisCache.setHourCache(key, id, hour);
            }
        } else if(state == 1) {
            String key = String.format(RedisKeys.FORBID_USER_LOGIN, id);
            redisCache.deleteObject(key);
        }
        appUser.setStates(state);
        appUserMapper.updateById(appUser);
    }
}
